<template>
  <div>
    <el-drawer
      v-model="visible"
      :title="title"
      @close="onDrawClose"
    >
      <div class="scene-dialog">
        <el-form
          ref="formIns"
          :model="form"
          :rules="rules"
          label-width="100"
          label-position="top"
        >
          <el-form-item label="变量属性">
            <div class="attr-container">
              <!-- 类型 -->
              <el-select
                v-model="form.varType"
                placeholder="变量表类型"
                clearable
                @change="onVarTypeChange"
              >
                <el-option
                  v-for="i of varTypeList"
                  :key="i"
                  :label="i"
                  :value="i"
                />
              </el-select>
              <!-- 名称 -->
              <el-select
                v-model="typeName"
                :disabled="!form.varType"
                clearable
                placeholder="变量名称"
              >
                <el-option
                  v-for="i of typeNameList"
                  :key="i"
                  :label="i"
                  :value="i"
                />
              </el-select>
            </div>
          </el-form-item>

          <el-form-item
            label="变量单位"
            prop="varUnit"
          >
            <el-input
              v-model="form.varUnit"
              :disabled="disabledUnitAndJson"
            />
          </el-form-item>

          <el-form-item
            label="变量名称"
            prop="varName"
          >
            <el-input v-model="form.varName" />
          </el-form-item>

          <el-form-item
            label="变量标识"
            prop="varJson"
          >
            <el-input
              v-model="form.varJson"
              :disabled="disabledUnitAndJson"
            />
          </el-form-item>

          <el-form-item
            label="变量序号"
            prop="varSort"
          >
            <el-input-number v-model="form.varSort" />
          </el-form-item>

          <el-form-item
            label="系数"
            prop="coefficient"
          >
            <el-input-number v-model="form.coefficient" />
          </el-form-item>

          <el-form-item
            label="数据格式"
            prop="dataFormat"
          >
            <el-select
              v-model="form.dataFormat"
              placeholder="请选择"
            >
              <el-option
                v-for="i of dataFormatList"
                :key="i.value"
                :label="i.name"
                :value="i.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="数字格式"
            prop="numberFormat"
          >
            <el-select
              v-model="form.numberFormat"
              placeholder="请选择"
            >
              <el-option
                v-for="i of numberFormatList"
                :key="i.value"
                :label="i.name"
                :value="i.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="读写方式"
            prop="readWriteMode"
          >
            <el-radio-group v-model="form.readWriteMode">
              <el-radio :value="1">读写</el-radio>
              <el-radio :value="2">只读</el-radio>
              <el-radio :value="3">只写</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >
          提交
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { validate } from '@/utils/validate';
import {
  apiAddVar,
  apiGetVarDetail,
  apiGetVarNameList,
  apiGetVarTypeList,
  apiGetVarUnitAndJson,
  apiUpdateVar,
  VarItem,
} from "@/api/var";
import {
  apiGetDataFormatList,
  DataDictionaryItem,
  dataDictionaryMode,
} from "@/api/common";

// init data
const form = reactive<VarItem>({
  // 变量属性（左）
  varType: "",
  // 变量名称
  varName: "",
  // 变量单位，接口查
  varUnit: "",
  // 变量标识，接口查
  varJson: "",
  // 变量id，接口查
  varId: 0,
  // 变量序号
  varSort: 0,
  // 系数
  coefficient: 0,
  // 数据格式
  dataFormat: "",
  // 数字格式
  numberFormat: "",
  // 读写方式，1-读写，2-只读，3-只写
  readWriteMode: 1,
});

// form ins
const formIns = ref<FormInstance>();
const onDrawClose = () => {
  formIns.value?.resetFields();
  form.varType = "";
  typeName.value = "";
};

const visible = ref(false);
const title = ref("新增");

// 变量属性（type）相关
const varTypeList = ref<string[]>([]);
const onVarTypeChange = async (v: string) => {
  const res = await apiGetVarNameList(`${v}`);
  typeNameList.value = res.data.date;
  typeName.value = "";
};
// 变量type对应name 相关
const typeName = ref("");
const typeNameList = ref<string[]>([]);
const getUnitAndJson = async (type: string, name: string) => {
  const res = await apiGetVarUnitAndJson({
    name,
    type,
  });
  form.varJson = res.data.identJson;
  form.varUnit = res.data.unit;
  form.varId = res.data.id;
  // form.varName = res.data.name;
};
watch(
  () => typeName.value,
  async (v) => {
    getUnitAndJson(form.varType, v);
  },
);

// 变量数据格式 相关
const dataFormatList = ref<DataDictionaryItem[]>([]);
const getDataFormatList = async () => {
  const res = await apiGetDataFormatList(dataDictionaryMode["数据格式"]);
  dataFormatList.value = res.data;
};
getDataFormatList();
// 变量数字格式 相关
const numberFormatList = ref<DataDictionaryItem[]>([]);
const getNumberFormatList = async () => {
  const res = await apiGetDataFormatList(dataDictionaryMode["数字格式"]);
  numberFormatList.value = res.data;
};
getNumberFormatList();

// 变量标识、变量单位 是否能修改取决于最上方的变量属性
const disabledUnitAndJson = computed(() =>
  Boolean(form.varType && typeName.value),
);

const init = async ({
  id,
  templateId,
}: {
  id?: number;
  templateId?: number;
}) => {
  visible.value = true;
  // 数据回显
  if (id) {
    title.value = "编辑";
    const res = await apiGetVarDetail(id);
    typeName.value = res.data.name;
    Reflect.deleteProperty(res.data, "type");
    Reflect.deleteProperty(res.data, "name");
    Object.assign(form, res.data);
    const res2 = await apiGetVarNameList(res.data.varType)
    typeNameList.value = res2.data.date;
  } else if (templateId) {
    form.templateId = templateId;
  }

  // 初始化 变量属性数据
  const res = await apiGetVarTypeList();
  varTypeList.value = res.data.date;
};

defineExpose({ init });

const emit = defineEmits<{ (e: "refresh"): void }>();
const submit = async () => {
  const api = title.value == "新增" ? apiAddVar : apiUpdateVar;
  // 兼容 undefined
  if (!form.varType) form.varType = "";
  const valid = await validate(formIns);
  if (valid) {
    const res = await api(form);
    ElMessage.success(res.msg);
    visible.value = false;
    emit("refresh");
  }

};

const rules = reactive({
  varName: [{ required: true, message: "请输入变量名称", trigger: "blur" }],
  varJson: [{ required: true, message: "请输入变量标识", trigger: "blur" }],
  coefficient: [{ required: true, message: "请输入系数", trigger: "blur" }],
  dataFormat: [
    { required: true, message: "请选择数据格式", trigger: "change" },
  ],
  numberFormat: [
    { required: true, message: "请选择数字格式", trigger: "change" },
  ],
  readWriteMode: [
    { required: true, message: "请选择读写方式", trigger: "change" },
  ],
});
</script>
<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 20px;
}
:deep(.el-drawer__body) {
  padding-top: 0px;
}
:deep(.el-drawer__footer) {
  text-align: center;
}

.attr-container {
  display: flex;
  width: 100%;
}
</style>
